<script setup name="login">
import { onActivated, onDeactivated, reactive, ref } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { CODE_WAIT_TIME } from '@/constants';
import { throttle } from 'lodash';
import * as useApi from '@/api/user';
import * as strategy from '@/constants/strategy';

const store = useStore();
const router = useRouter();

const mode = ref('account'); // 'account' | 'message'
const countDown = ref(CODE_WAIT_TIME);


const form = ref(null);

const account = localStorage.getItem('account') || '';
const password = localStorage.getItem('password') || '';
const isMemo = localStorage.getItem('isMemo') === 'true' || true;
const activeName = ref('first');

// keep-alive包裹的组件才会有activated和deactivated生命周期
onActivated(() => {
  console.log(123);
  // 切过来
});

onDeactivated(() => {
  console.log(456);
  // 切走
});
const params = reactive({
  account: isMemo ? account : '',
  password: isMemo ? password : '',
  code: '',
  isMemo,
  isAgree: false,
});

function accountChecker(_, value, cb) {
  if (!strategy.ACCOUNT.test(value.trim())) {
    cb(new Error('账号格式错误 应为字母开头 共6-20个字符'));
  } else {
    cb();
  }
}

function mobileChecker(_, value, cb) {
  if (!strategy.MOBILE.test(value.trim())) {
    cb(new Error('手机号格式错误'));
  } else {
    cb();
  }
}

function codeChecker(_, value, cb) {
  if (!strategy.CODE.test(value.trim())) {
    cb(new Error('验证码格式错误'));
  } else {
    cb();
  }
}

function agreeChecker(_, value, cb) {
  if (!value) {
    cb(new Error('不同意不行'));
  } else {
    cb();
  }
}
const rules = reactive({
  account: [{ validator: accountChecker, trigger: 'blur' }],
  mobile: [{ validator: mobileChecker, trigger: 'blur' }],
  code: [{ validator: codeChecker, trigger: 'blur' }],
  isAgree: [{ validator: agreeChecker, trigger: 'change' }],
});


function onLoginWithAccount() {
  form.value.validate(async (valid) => {
    if (valid) {
      const res = await store.dispatch('user/login', params);
      if (res.success) {
        // 如果勾选了记住我，就记录相关数据
        if (params.isMemo) {
          localStorage.setItem('account', params.account);
          localStorage.setItem('password', params.password);
          localStorage.setItem('isMemo', params.isMemo);
        }
      } else {
        params.password = '';
      }
    }
    router.push('/homepage');
  });
}
// 发送验证码
const sendCodeWithCheckSuccess = throttle(() => {
  let timer = null;
  useApi.loginWithCode(params.mobile)
    .then((msg) => {
      ElMessage({
        message: msg,
        type: 'success',
      });
    })
    .cath((msg) => {
      sendCodeWithCheckSuccess.cancel();
      clearInterval(timer);
      countDown.value = CODE_WAIT_TIME;
      ElMessage({
        message: msg,
        type: 'error',
      });
    });
  countDown.value = CODE_WAIT_TIME - 1;
  timer = setInterval(() => {
    countDown.value--;
    if (countDown.value < 1) {
      clearInterval(timer);
      countDown.value = CODE_WAIT_TIME;
    }
  }, 1000);
}, CODE_WAIT_TIME * 1000);
function sendCode() {
  if (!strategy.MOBILE.test(params.mobile)) {
    return;
  }
  // 成功
  sendCodeWithCheckSuccess();
}
function useMessage() {
  mode.value = 'message';
}
function useAccount() {
  mode.value = 'account';
}
</script>

<template>
  <div>
    <div class="rabbit-beij"></div>
  </div>
  <div class="beijin">
    <div class="container">
      <div class="form-wrapper">

        <el-tabs
          v-model="activeName"
          class="demo-tabs"
        >
          <el-tab-pane
            label="账户登录"
            name="first"
          >
            账户登录
          </el-tab-pane>
          <el-tab-pane
            label="扫码登录"
            name="second"
          >
            扫码登录
          </el-tab-pane>
        </el-tabs>

        <el-form
          ref="form"
          :rules="rules"
          :model="params"
        >
          <template v-if="mode === 'account'">
            <el-button
              class="shiyon"
              @click="useMessage"
            >
              使用短信登录
            </el-button>
            <el-form-item>
              <el-input
                v-model="params.account"
              >
                <template #prepend>
                  <i-ep-user class="icon" />
                </template>
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-input
                v-model="params.password"
                type="password"
              >
                <template #prepend>
                  <i-ep-lock class="icon" />
                </template>
              </el-input>
            </el-form-item>
          </template>
          <template v-else>
            <el-button
              class="shiyon"
              @click="useAccount"
            >
              使用账户登录
            </el-button>
            <el-form-item prop="mobile">
              <el-input
                v-model="params.mobile"
              >
                <template #prepend>
                  <i-ep-user class="icon" :size="24"/>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="code">
              <el-input
                v-model="params.code"
              >
                <template #prepend>
                  <icon name="dun-pai" :size="24 * .9" color="#fff" />
                </template>
                <template #append>
                  <el-button
                    @click="sendCode"
                    :disabled="countDown !== CODE_WAIT_TIME"
                  >
                    {{ countDown === CODE_WAIT_TIME ? '发送验证码' : countDown }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </template>

          <el-form-item>
            <el-checkbox
              v-model="params.isMemo"
              label="记住我"
            />
          </el-form-item>

          <el-form-item>
            <el-checkbox v-model="params.isAgree">
              我已同意
              <a href="">《隐私条款》</a>
              和
              <a href="">《服务条款》</a>
            </el-checkbox>
          </el-form-item>

          <el-button
            class="goLogin"
            type="primary"
            :disabled="!params.isAgree"
            @click="() => mode === 'account' ? onLoginWithAccount() : onLoginWithCode()"
          >
            登录
          </el-button>
        </el-form>

      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.rabbit-beij {
  overflow: hidden;
  height: 132px;
  width: 200px;
  background: url(http://erabbit.itheima.net/img/logo.0940ebb5.png);
}
.beijin {
  background: url(http://erabbit.itheima.net/img/login-bg.696efec3.png);
  height: 488px;
  .container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;

    .form-wrapper {
      width: 380px;
      background-color: white;

      .demo-tabs > .el-tabs__content {
        padding: 32px;
        color: #6b778c;
        font-size: 32px;
        font-weight: 600;
      }
      :deep(.el-input-group__prepend) {
        background-color: #cfcdcd;
        padding: 8px;
      }
      .shiyon {
        margin-left: 255px;
        margin-bottom: 10px;
      }
      .icon {
        font-size: 18px;
        color: white;
      }
    }
    .goLogin {
      width: 300px;
      height: 40px;
      margin-left: 35px;
    }
  }
}

</style>
